<template>
  <el-dialog v-model="visible" :title="!dataForm.pid ? $t('add') : $t('update')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()" label-width="120px">
      <el-form-item label="上级分类" prop="parentName">
        <el-popover :width="400" ref="categoriesListPopover" placement="bottom-start" trigger="click" popper-class="popover-pop">
          <template v-slot:reference>
            <el-input v-model="dataForm.parentName" :readonly="true" placeholder="上级分类">
              <template v-slot:suffix>
                <el-icon @click.stop="deptListTreeSetDefaultHandle()" class="el-input__icon"><circle-close /></el-icon>
              </template> </el-input>
          </template>
          <div class="popover-pop-body"><el-tree :data="categoriesList" :props="{ label: 'name', children: 'children' }" node-key="id" ref="categoriesTree" :highlight-current="true" :expand-on-click-node="false" accordion @current-change="deptListTreeCurrentChangeHandle"> </el-tree></div>
        </el-popover>
      </el-form-item>
      <el-form-item label="分配门店"  prop="storeId">
        <el-select v-model="dataForm.storeId" placeholder="分配门店">
          <el-option :label="data.storeName" v-for="data in storeList" :key="data.storeId" :value="data.storeId">{{ data.storeName }}</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="dataForm.name" placeholder="分类名称"></el-input>
      </el-form-item>
      <el-form-item label="分类描述" prop="description">
        <el-input v-model="dataForm.description" placeholder="分类描述"></el-input>
      </el-form-item>
      <el-form-item label="是否启用" prop="isActive">
        <ren-radio-group v-model="dataForm.isActive" dict-type="is_active"></ren-radio-group>
      </el-form-item>
      <el-form-item label="分类图片URL" prop="imageUrl">
        <el-input v-model="dataForm.imageUrl" placeholder="分类图片URL"></el-input>
      </el-form-item>
      <el-form-item label="排序字段，默认值为0" prop="sortOrder">
        <el-input v-model="dataForm.sortOrder" placeholder="排序字段，默认值为0"></el-input>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import baseService from "@/service/baseService";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);
const categoriesListPopover = ref();

const visible = ref(false);
const dataFormRef = ref();
const categoriesList:any = ref([]);
const storeList = ref();

const dataForm:any = reactive({
  id: null,
  pid: null,
  parentName: "",
  tenantId: "",
  storeId: "",
  name: "",
  description: "",
  isActive: 1,
  imageUrl: "",
  sortOrder: "",
  createDate: "",
  updateDate: "",
  creator: "",
  updator: "",
});

const rules = ref({
  "parentName": [{ required: true, message: t("validate.required"), trigger: "blur" }],
  "name": [{ required: true, message: t("validate.required"), trigger: "blur" }],
  "storeId": [{ required: true, message: t("validate.required"), trigger: "blur" }],
});

const init = (id?: number) => {
  visible.value = true;
  dataForm.id = "";

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }
  getCategoriesList().then(() => {
    if (id) {
      getInfo(id);
    }
  });
  getStoreList()

};

// 获取客户端信息
const getStoreList = () => {
  baseService.get("/sys/sysstore/list", {}).then((res) => {
    if (res.code === 200) {
      storeList.value = res.data;
    }
  });
};

// 获取分类列表
const getCategoriesList = () => {
  return baseService.get("/sys/zycategories/list").then((res:any) => {
    if (res.code !== 200) {
      return ElMessage.error(res.msg);
    }
    categoriesList.value =  [{pid: 0, name: "一级分类" }, ...res.data];
  });
};

const deptListTreeSetDefaultHandle = () => {
  dataForm.pid = "0";
  dataForm.parentName = "一级分类";
};

// 上级部门树, 选中
const deptListTreeCurrentChangeHandle = (data: any) => {
  if (data.id == null) {
    dataForm.pid = data.pid;
    dataForm.parentName = data.name;
  } else {
    dataForm.pid = data.id;
    dataForm.parentName = data.name;
  }
 
  categoriesListPopover.value.hide();
};

// 获取信息
const getInfo = (id: number) => {
  baseService.get("/sys/zycategories/" + id).then((res:any) => {
    Object.assign(dataForm, res.data);
    const {pid, name} = res.data;
    if (pid === "0") {
      dataForm.pid = pid;
      dataForm.parentName = "一级分类";
    } else {
      dataForm.pid = pid;
      dataForm.parentName = name;
    }
  });
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    (!dataForm.id ? baseService.post : baseService.put)("/sys/zycategories", dataForm).then((res) => {
      ElMessage.success({
        message: t("prompt.success"),
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};

defineExpose({
  init
});
</script>